package info.leetcode.answer.Array.statistics;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Classname FindShortestSubArray
 * @Description 数组的度
 * @Date 2024/1/16 14:26
 * @Created by 晓龙Oba
 */
public class FindShortestSubArray {
    public static void main(String[] args) {
        int[] nums = {1, 2, 2, 3, 1, 4, 2};
        int result = findShortestSubArray(nums);
        System.out.println(result);
    }

    private static int findShortestSubArray(int[] nums) {
        int result = 0;
        Map<Integer, int[]> map = new HashMap<>();
        TreeMap<Integer, Integer> sortMap = new TreeMap<>();
        for (int i = 0; i < nums.length; i++) {
            int[] item = map.get(nums[i]);
            if (item == null) {
                item = new int[]{1, i, i};
                map.put(nums[i], item);
                sortMap.put(1, 1);
            } else {
                item[0] += 1;
                item[2] = i;
                Integer temporary = sortMap.get(item[0]);
                sortMap.put(item[0], temporary == null || item[2] - item[1] + 1 < temporary ? item[2] - item[1] + 1 : temporary);
            }
        }

        return sortMap.get(sortMap.lastKey());

    }
}
